package hk.com.carfield.web;

import hk.com.carfield.util.FileObject;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.util.StringUtil;

import java.util.Collection;

public abstract class Request {
	public static final int DEFAULT_ITEM_PER_PAGE = 25;
	private final String pwd;

	protected Request(final String pwd) {
		super();
		this.pwd = pwd;
	}

	public abstract String clientIP();

	public final boolean getBoolean(final String name) {
		return StringUtil.getBoolean(getParameter(name));
	}

	public abstract Collection<FileObject> getFileObject();

	public final int getInt(final String name) {
		try {
			if (StringUtil.notBlank(name)) {
				return Integer.parseInt(getParameter(name));
			} else {
				return 0;
			}
		} catch (final NumberFormatException e) {
			LogUtil.log(e.getMessage());
			return 0;
		}
	}

	public abstract String getParameter(final String name);

	private String getPassword() {
		return getSessionValue("password") == null ? ""
				: getSessionValue("password");
	}

	protected abstract String getSessionValue(final String name);

	public abstract String host();

	public final boolean isAdminEnable() {
		return pwd == null ? false : pwd.equals(getPassword());
	}

	public int itemsOfPage() {
		return isAdminEnable() ? Integer.MAX_VALUE
				: Request.DEFAULT_ITEM_PER_PAGE;
	}

	public final void setPassword(final String password) {
		setSessionValue("password", password);
	}

	protected abstract void setSessionValue(final String name,
			final String value);

	@Override
	public String toString() {
		return "\npwd: " + getPassword() + "\nIP: " + clientIP();
	}
}
